package cn.cms.chuangjia.front;

import cn.cms.chuangjia.domain.Article;
import cn.cms.chuangjia.domain.Menu;
import cn.cms.chuangjia.service.IArticleService;
import cn.cms.chuangjia.service.IMenuService;
import cn.cms.chuangjia.util.StrUtil;
import cn.cms.chuangjia.vo.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
@Controller
//@RequestMapping("front")
public class FrontMenuController {
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IArticleService articleService;

    @GetMapping("main")
    public String list(Menu menu, Model model){
        List<Menu> menus = menuService.selectMenuTree(menu);
        model.addAttribute("menus", menus);
        //return "index";
        List<Article> tuijianProduct = articleService.findTuijianProduct(6);
        model.addAttribute("tuijianProduct", tuijianProduct);
        model.addAttribute("topnews", articleService.findNews(4));
        model.addAttribute("product", articleService.findProduct(4));
        model.addAttribute("customers", articleService.findCustomers(4));

        return "main";
    }
    @GetMapping("type-{id}-{child}")
    public String get(@PathVariable("id")Integer id,@PathVariable("child") Integer child, Model model){
        //
        List<Menu> menus = menuService.selectMenuTree(null);
        model.addAttribute("menus", menus);
        //
        Menu menu = menuService.selectMenu(id);
        model.addAttribute("menu", menu);
        model.addAttribute("id", id);
        model.addAttribute("child", child);
        model.addAttribute("menu2", menuService.selectMenu(child));

        startPage();
        List<Article> list = articleService.selectArticleByMenu(child);
        Page<Article> page = Page.convert(PageInfo.of(list));
        model.addAttribute("page", page);
        return "articles";
    }

    public void startPage() {
        HttpServletRequest request =
                ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        int pageNo = StrUtil.toInt(page, 1);
       // int pageSize = StrUtil.toInt(limit, 12);
        int pageSize = StrUtil.toInt(limit, 2);
        PageHelper.offsetPage(pageSize * (pageNo - 1), pageSize);
    }
}
